package cn.body.daw.filter;

import cn.body.daw.config.IgnoreWhitesProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author: lvye
 * @createDate: 2024-10-12
 * @FileName: GatewayFilter
 * 自定义内容:
 */
@Slf4j
@Component
public class GatewayFilter implements GlobalFilter, Ordered {
    @Autowired
    private IgnoreWhitesProperties ignoreWhitesProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求、响应对对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        List<String> whites = ignoreWhitesProperties.getWhites();
        log.info("打印读取到的白名单配置=={}",whites.toString());

        //跳过不需要验证的路径,即白名单
        String reqPath = request.getURI().getPath();
        log.info("获取到的请求路径=={}",reqPath);
        if(whites.contains(reqPath)){
            log.info("请求路径在白名单内,放行");
            return chain.filter(exchange);
        }

        //token校验
        log.info("token校验开始");
        String token = request.getHeaders().getFirst("Authorization");
        if(StringUtils.isBlank(token)){
            //没用令牌 响应http状态码401
            log.info("token为空,拦截返回401状态码");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        return null;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
